package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Companion;
import cn.wolfcode.trip.base.domain.CompanionRequest;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.CompanionMapper;
import cn.wolfcode.trip.base.mapper.CompanionRequestMapper;
import cn.wolfcode.trip.base.query.CompanionQueryObject;
import cn.wolfcode.trip.base.service.ICompanionService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CompanionServiceImpl implements ICompanionService{


    @Autowired
    private CompanionMapper companionMapper;

    @Autowired
    private CompanionRequestMapper requestMapper;

    @Override
    public PageInfo<Companion> query(CompanionQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<Companion> list = companionMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public Companion selectById(Long companionId) {
        return companionMapper.selectByPrimaryKey(companionId);
    }


    @Override
    public void saveOrUpdate(Companion companion) {
        if (companion.getId() != null) {
            companionMapper.updateByPrimaryKey(companion);
            CompanionRequest request = companion.getRequest();
            request.setId(companion.getId());
            requestMapper.updateByPrimaryKey(request);
        }else {
            companion.setAuthor(UserContext.getCurrentUser());
            companionMapper.insert(companion);
            requestMapper.insert(companion.getId(),companion.getRequest().getRequest());
        }
    }
}
